package com.example.mybatis.controller;

import cn.dev33.satoken.sso.SaSsoManager;
import cn.dev33.satoken.sso.model.SaCheckTicketResult;
import cn.dev33.satoken.sso.processor.SaSsoClientProcessor;
import cn.dev33.satoken.sso.template.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.example.mybatis.utils.ResultUtil;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 前后端分离架构下集成SSO所需的接口
 */
@RestController
public class LoginController {

    // 当前是否登录
    @RequestMapping("/sso/isLogin")
    public Object isLogin() {
        return SaResult.data(StpUtil.isLogin());
    }

    // 返回SSO认证中心登录地址
    @RequestMapping("/sso/getSsoAuthUrl")
    public ResultUtil getSsoAuthUrl(String clientLoginUrl) {
        String serverAuthUrl = SaSsoUtil.buildServerAuthUrl(clientLoginUrl, "");
        return ResultUtil.ok().put("data",serverAuthUrl);
    }

    // 根据ticket进行登录
    @RequestMapping("/sso/doLoginByTicket")
    public ResultUtil doLoginByTicket(String ticket) {
        SaCheckTicketResult ctr = SaSsoClientProcessor.instance.checkTicket(ticket, "/sso/doLoginByTicket");
        StpUtil.login(ctr.loginId, ctr.remainSessionTimeout);
        return ResultUtil.ok().put("data",StpUtil.getTokenValue());
    }

    // 根据ticket进行登录
    @RequestMapping("/sso/logout")
    public void doLogoutByToken(String satoken, String back, HttpServletResponse response) throws IOException {
        String solUrl = SaSsoManager.getClientConfig().splicingSloUrl();

        StpUtil.logoutByTokenValue(satoken);
        response.sendRedirect(solUrl + "?back=" + back);
    }

    // 全局异常拦截
    @ExceptionHandler
    public SaResult handlerException(Exception e) {
        e.printStackTrace();
        return SaResult.error(e.getMessage());
    }

}
